package com.api.demo.service.impl;

import com.api.demo.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Value("${file.upload-dir:uploads/avatars}")
    private String uploadDir;

    @Override
    public String storeAvatar(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                throw new RuntimeException("Cannot store empty file");
            }

            // 创建绝对路径的上传目录
            String absolutePath = new File("").getAbsolutePath();
            Path uploadPath = Paths.get(absolutePath, uploadDir);
            System.out.println("Upload directory path: " + uploadPath);
            
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
                System.out.println("Created directory: " + uploadPath);
            }

            // 生成唯一文件名
            String originalFilename = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
            String fileExtension = getFileExtension(originalFilename);
            String newFilename = UUID.randomUUID() + fileExtension;
            System.out.println("Generated filename: " + newFilename);

            // 保存文件
            Path targetLocation = uploadPath.resolve(newFilename);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("File saved to: " + targetLocation);

            // 返回可访问的URL
            return "/api/files/avatars/" + newFilename;
        } catch (IOException ex) {
            System.err.println("Error storing file: " + ex.getMessage());
            ex.printStackTrace();
            throw new RuntimeException("Failed to store file", ex);
        }
    }

    private String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf('.');
        if (dotIndex < 0) {
            return "";
        }
        return filename.substring(dotIndex);
    }
} 